package baiqitun.stupro.api.controller;

import baiqitun.stupro.common.entity.impl.SysFile;
import baiqitun.stupro.common.service.system.SysFileService;
import baiqitun.stupro.common.util.AuthUtil;
import baiqitun.stupro.common.util.UploadUtil;
import baiqitun.stupro.security.entity.SysUser;
import baiqitun.stupro.security.service.SysUserService;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpStatus;
import org.springframework.security.core.Authentication;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletRequest;
import javax.validation.constraints.NotBlank;
import java.io.IOException;

/**
 * 通用控制器
 * @author kedaji
 */
@RequestMapping("/file")
@Api(description = "文件控制器")
@Slf4j
@Controller
public class FileController {
    @Autowired
    private SysUserService sysUserService;
    @Autowired
    private SysFileService sysFileService;

    @ResponseStatus(HttpStatus.OK)
    @ApiOperation("上传文件")
    @PostMapping
    public void upload(Authentication authentication, HttpServletRequest request) throws IOException {
        String username = AuthUtil.getUsername(authentication);
        SysUser user = sysUserService.getUserByUsername(username);
        MultipartFile file = UploadUtil.single(request);
        SysFile fileRecord = new SysFile();
        fileRecord.setFilename(file.getOriginalFilename()).setUserId(user.getId()).setCreateBy(username);
        sysFileService.save(fileRecord, file.getInputStream());
    }

    @ResponseStatus(HttpStatus.OK)
    @ApiOperation("删除文件")
    @DeleteMapping
    public void removeById(Authentication authentication,  @NotBlank(message = "文件id不能为空") String fileId){
        String username = AuthUtil.getUsername(authentication);
        sysFileService.removeById(fileId, username);
    }

    @ResponseStatus(HttpStatus.OK)
    @ApiOperation("我的上传")
    @GetMapping
    public void pageMyFiles(Authentication authentication, Integer pageNo, Integer pageSize){

    }
}
